<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\Controller;
use App\Models\Activity;
use App\Models\Device;
use App\Models\Order;
use App\Models\OrderUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    //订单列表
    public function getOrderList(Request $request){

//        $pay_status = $request->pay_status; //支付状态 0未支付 1已支付
//        $order_status = $request->pay_status; //订单状态   0待核销  1部分核销 2已完成'
        $keywords = $request->keywords; //搜索关键字 name姓名 或者 mobile 用户手机号 或者 order_sn 订单编号

//        $start_time = $request->start_time;
//        $end_time = $request->end_time;

        $where = function($query) use ($request){
            if($request->pay_status || $request->pay_status===0||$request->pay_status==='0'){
                $query->where('pay_status',$request->pay_status);
            }
            if($request->order_status|| $request->order_status===0||$request->order_status==='0'){
                $query->where('order_status',$request->order_status);
            }
            if($request->check_status){
                $query->where('check_status',$request->check_status);
            }
            if($request->start_time&&$request->end_time){
                $query->whereBetween('created_at',[$request->start_time,$request->end_time]);
            }
            if($request->activity_id){

                 $query->where('activity_id',$request->activity_id);
            }

        };

        $list = Order::with(['user:id,mobile,name,nickname','activity:id,title'])->where($where)->
            when($keywords,function($query) use ($keywords){
                $query->where(function ($query) use ($keywords){
                    return $query->whereHas('user', function ($query) use ($keywords) {
                        return $query->where('mobile', 'like', '%'.$keywords.'%');
                    })->orWhereHas('activity',function ($query) use ($keywords){
                        return $query->Where('title', 'like', '%'.$keywords.'%');
                    });
                });

            })
           ->select(['id','order_sn','user_id','activity_id','money','person','pay_status','check_status','order_status','province','city','district','pay_time','created_at'])
            ->orderBy('id','desc')->paginate($request->pageSize?:15);

       return $this->success($list);
    }


    //获取订单详情
    public function getOrderInfo(Request $request){
        $order_id = $request->order_id;

        if(!$order_id)
            return $this->failed('参数不全');

        $order = Order::with(['user:id,mobile,name,header_img','order_user'])->find($order_id);


        return $this->success($order);
    }



    //根据二维码获取购票人信息
    public function getInfoFromQr(Request $request){
        $data = $request->msg;

        try {
            $data = explode(',',base64_decode($data));
        }catch (\Exception $e){
            return $this->failed("无效二维码");
        }

        $order = Order::find($data[0]);

        if(!$order)
            return $this->failed("二维码不合法");


        $order_user = OrderUser::find($data[1]);

        if(!$order_user)
            return $this->failed("二维码有误");

        if($order_user->status==1)
            return $this->failed("二维码已核销");

        $activity = Activity::find($order->activity_id);

        return $this->success(['name'=>$order_user->name,'mobile'=>$order_user->mobile,'keys'=>$activity->keys,'values'=>$order_user->values]);
    }

    //二维码核销
    public function ckeckQrCode(Request $request){

        $data = $request->msg;
        $activity_id = $request->activity_id;

        $data = explode(',',base64_decode($data));


        $order = Order::find($data[0]);

        if(!$order)
            return $this->failed("二维码不合法");

        if($order->activity_id != $activity_id)
            return $this->failed("非本活动订单");

        if($order->pay_status<1)
            return $this->failed("订单未支付");

        if($order->check_status==1)
            return $this->failed("订单状态待审核");

//        if(time()-$data[2] > 70)
//            return $this->failed("二维码已失效");

        $order_user = OrderUser::find($data[1]);

        if(!$order_user)
            return $this->failed("二维码有误");


        if($order_user->status==1)
            return $this->failed("二维码已核销");

        $order_user->status = 1;
        $order_user->check_time = date("Y-m-d H:i:s");
        $res1 = $order_user->save();

       $order_users = OrderUser::where('order_id',$data[0])->get();

       $flag = true;
       foreach ($order_users as $k=>$v){
            if($v['status']==0){
                $flag = false;
                break;
            }

       }
       if($flag){
           $order->order_status = 2;
       }else{
           $order->order_status = 1;
       }

        $order->save();

       return $this->success("核销成功");

    }

    public function ckeckQr(Request $request){


        $data=file_get_contents("php://input");

        file_put_contents("/www/wwwroot/activity/pay.log",date("H:i:s").$data."\r\n",FILE_APPEND);
        file_put_contents("/www/wwwroot/activity/pay.log",date("H:i:s").preg_replace("/[\n\s]+/", "", $data)."\r\n",FILE_APPEND);
        $data = json_decode(preg_replace("/[\n\s]+/", "", $data),true);


        //$activity_id = $request->activity_id;
        //$device_id = $request->id;

        try {
            $device_id = $data['id'];
            $data = $data['code'];
            $data = explode(',',base64_decode($data));
        }catch (\Exception $e){
            return $this->respond(['result'=>0,'vol_msg'=>"二维码不合法"]);
        }






        $order = Order::find($data[0]);

        if(!$order)
            return $this->respond(['result'=>0,'vol_msg'=>"二维码不合法"]);
            //return $this->failed("二维码不合法");

        $activity = Activity::find($order->activity_id);
        $device = Device::where('device_id',$device_id)->first();
        if(!$device || !$activity->device_id)
            return $this->respond(['result'=>0,'vol_msg'=>"非本活动"]);
        if(!in_array($device->id,explode(',',$activity->device_id)))
            return $this->respond(['result'=>0,'vol_msg'=>"非本活动"]);
//        if($order->activity_id != $activity_id)
//            return $this->failed("非本活动订单");

        if($order->pay_status<1)
            //return $this->failed("订单未支付");
            return $this->respond(['result'=>0,'vol_msg'=>"订单未支付"]);

        if($order->check_status==1)
            //return $this->failed("订单状态待审核");
            return $this->respond(['result'=>0,'vol_msg'=>"订单状态待审核"]);

//        if(time()-$data[2] > 70)
//            //return $this->failed("二维码已失效");
//            return $this->respond(['result'=>0,'vol_msg'=>"二维码已失效"]);

        $order_user = OrderUser::find($data[1]);

        if(!$order_user)
            return $this->respond(['result'=>0,'vol_msg'=>"二维码有误"]);
            //return $this->failed("二维码有误");


        if($order_user->status==1)
            return $this->respond(['result'=>0,'vol_msg'=>"二维码已核销"]);
            //return $this->failed("二维码已核销");

        $order_user->status = 1;
        $order_user->check_time = date("Y-m-d H:i:s");
        $res1 = $order_user->save();

        $order_users = OrderUser::where('order_id',$data[0])->get();

        $flag = true;
        foreach ($order_users as $k=>$v){
            if($v['status']==0){
                $flag = false;
                break;
            }

        }
        if($flag){
            $order->order_status = 2;
        }else{
            $order->order_status = 1;
        }

        $order->save();


        return $this->respond(['result'=>0,'vol_msg'=>"核验成功",'vol_index'=>2]);

    }

    public function AutoCheck(Request $request){
        $id = $request->id;
        if(!$id)
            return $this->failed('mobile必传');
        $order_user = OrderUser::where('id',$id)->first();

        if(!$order_user)
            return $this->failed('数据不存在');
        //return $this->success($order_user);
        $order = Order::find($order_user->order_id);

        $order_user->status = 1;
        $order_user->check_time = date("Y-m-d H:i:s");
        $order_user->save();
        $order_users = OrderUser::where('order_id',$order->id)->get();

        $flag = true;
        foreach ($order_users as $k=>$v){
            if($v['status']==0){
                $flag = false;
                break;
            }

        }
        if($flag){
            $order->order_status = 2;
        }else{
            $order->order_status = 1;
        }

        $order->save();
        return $this->success('核销成功');
    }


    //报名名单列表
    public function getOrderUser(Request $request){

        $mobile = $request->mobile; //手机号查询
        $title = $request->title; //活动名称
        $title = $request->status; //核销状态  待核销 已核销  已退款

        $export = $request->export;


        $where = function($query) use ($request){
            if($request->mobile){//手机号查询

                $query->where('values', 'like', '%'.$request->mobile.'%');
            }
            if($request->activity_id){
                $query->where('activity_id',$request->activity_id);
            }
            if($request->name){//名字查询

                $query->where('values', 'like', '%'.$request->name.'%');

            }
            if($request->title){//活动名称
                $query->whereHas('activity', function ($query) use ($request) {
                    return $query->where('title', 'like', '%'.$request->title.'%');
                });
            }
            if($request->status || $request->status==='0' ||$request->status===0){
                $query->where('status',$request->status);
            }

            $query->where('pay_status',1);
        };


        if($export==1){ //excel导出
            $order_user = OrderUser::with(['order:id,order_sn,pay_status','activity:id,title,keys'])->where($where)->get();

            $title = ['活动名称','支付状态','核销状态','报名时间','核销时间'];
            $data = [];
            $key = [];
            if($order_user[0]->activity->keys){
                foreach ($order_user[0]->activity->keys as $k=>$v){

                    $key[] = explode('=>',$v)[0];
                }
            }
            $title = array_merge($title,$key);
            foreach ($order_user as $k=>$v){

                $data[$k][] = $v->activity->title;
//                $data[$k][] = $v->name;
//                $data[$k][] = $v->mobile;
//                if($v->activity->keys){
//                    $str = '';
//                    foreach ($v->activity->keys as $kk=>$vv){
//                        $str .= explode('=>',$vv)[0].':'.explode(',',$v->values)[$kk].',';
//                    }
//                    $str = mb_substr($str, 0, mb_strlen($str) - 1);
//                    $data[$k][] = $str;
//                }else{
//                    $data[$k][] = '';
//                }
                $data[$k][] = $v->order->pay_status?'已支付':'待支付';
                $data[$k][] =OrderUser::getStatusName($v->status);
                $data[$k][] = $v->created_at;
                $data[$k][] = $v->check_time;

                if($v->activity->keys){
                    foreach ($v->activity->keys as $kk=>$vv){

                        $data[$k][] = explode(',', $v->values)[$kk] ?? '';
                    }

                }else{
                    $data[$k][] = '';
                }

            }
            excelReport($title,$data,date("Y-m-d H:i:s"));die;
        }


        $order_user = OrderUser::with(['order:id,order_sn,pay_status,province,city,district','activity:id,title,keys'])->where($where)->orderBy('id','desc')->paginate($request->pageSize?:15);


        foreach ($order_user as $k=>$v){
            if($v->activity->keys){
                $str = '';
                foreach ($v->activity->keys as $kk=>$vv){
                    $str .= explode('=>',$vv)[0].',';
                }
                $str = mb_substr($str, 0, mb_strlen($str) - 1);
                $order_user[$k]['activity']['key'] = $str;
            }else{
                $order_user[$k]['activity']['key']='';
            }

        }

        return $this->success($order_user);
    }



    //订单审核
    public function CheckOrder(Request $request){
        $order_id = $request->order_id;
        $check_status = $request->check_status;//1待审核  2审核通过   3审核不通过

        if(!$order_id  || !$check_status)
            return $this->failed("订单id和状态必传");
        $order = Order::find($order_id);
        $activity = DB::table('activity')->find($order->activity_id);

        if(!$activity->check_rule)
            return $this->failed("该活动订单不需要审核");
        if($order->pay_status!=1)
            return $this->failed("未支付订单不能审核");
        if($order->order_status>0)
            return $this->failed("订单状态不能审核");

        $res = Order::where('id',$order_id)->update(['check_status'=>$check_status,'check_note'=>$request->check_note]);

        if($check_status==3){ //审核不通过 退款
            $user = new \App\Http\Controllers\Api\UserController();

            return $user->refundOrder($order_id);

        }

        if($res)
            return $this->success("操作成功");

        return $this->failed("操作失败");
    }


    public function testExport(){
        $activity = Activity::find(28);
        $order_user = OrderUser::find(91);
        return $this->success(['name'=>'李海强','mobile'=>'15921050479','keys'=>$activity->keys,'values'=>$order_user->values]);
    }

}
